﻿Public Class ChangePassword

    Private Sub ChangePassword_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If My.MySettings.Default.Password = String.Empty Then
            Me.Text = "Set Password"
            Me.TxtCurPwd.Text = String.Empty
            Me.TxtCurPwd.Enabled = False
        End If
    End Sub

    Private Sub BtnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOK.Click
        Try
            Dim curPwd As String = EncodePwd(Me.TxtCurPwd.Text.Trim())
            Dim pwd1 As String = EncodePwd(Me.TxtPwd1.Text.Trim())
            Dim pwd2 As String = EncodePwd(Me.TxtPwd2.Text.Trim())

            If Me.TxtPwd1.Text.Trim().Length = 0 Then
                Throw New InvalidOperationException("Invalid Password.")
            End If

            If My.MySettings.Default.Password.Length > 0 Then
                If String.Compare(curPwd, My.MySettings.Default.Password) <> 0 Then
                    Throw New InvalidOperationException("Current password does not match.")
                End If
            End If

            If String.Compare(pwd1, pwd2) <> 0 Then
                Throw New InvalidOperationException("Password confirmation failed.")
            End If
            My.MySettings.Default.Password = pwd1
            Me.DialogResult = DialogResult.OK
            Me.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

    Public Shared Function EncodePwd(ByVal text As String) As String
        Return Convert.ToBase64String((System.Security.Cryptography.MD5.Create()).ComputeHash(System.Text.Encoding.Default.GetBytes(text)))
    End Function

    Private Sub Inputs_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtPwd2.TextChanged, TxtPwd1.TextChanged, TxtCurPwd.TextChanged
        If My.MySettings.Default.Password = String.Empty Then
            Me.TxtCurPwd.Text = Me.TxtPwd1.Text
        End If
        Me.BtnOK.Enabled = (Me.TxtCurPwd.Text.Trim().Length > 0) AndAlso (Me.TxtPwd1.Text.Trim().Length > 0) AndAlso (Me.TxtPwd2.Text.Trim().Length > 0)
    End Sub

    Private Sub BtnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCancel.Click
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub
End Class